package com.xstudio.pvzreborn.network;

import com.xstudio.pvzreborn.capability.DaveCoin;
import com.xstudio.pvzreborn.capability.PlantFood;
import com.xstudio.pvzreborn.capability.Sunshine;
import com.xstudio.pvzreborn.utils.CapabilityUtils;
import com.xstudio.pvzreborn.utils.NetworkUtils;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.NetworkEvent.Context;

import java.util.function.Supplier;

public class PlayerCapabilityPacket extends PVZPacketBase {

	private final int sunshine;
	private final int daveCoin;
	private final int plantFood;

	private PlayerCapabilityPacket(LazyOptional<Sunshine> sunshine, LazyOptional<DaveCoin> daveCoin, LazyOptional<PlantFood> plantFood) {
		this.sunshine = sunshine.isPresent() ? sunshine.resolve().get().getValue() : 0;
		this.daveCoin = daveCoin.isPresent() ? daveCoin.resolve().get().getValue() : 0;
		this.plantFood = plantFood.isPresent() ? plantFood.resolve().get().getValue() : 0;
	}

	public PlayerCapabilityPacket(Player player) {
		this(CapabilityUtils.getSunshine(player), CapabilityUtils.getDaveCoin(player), CapabilityUtils.getPlantFood(player));
	}

	public PlayerCapabilityPacket(FriendlyByteBuf buf) {
		this.daveCoin = buf.readVarInt();
		this.sunshine = buf.readVarInt();
		this.plantFood = buf.readVarInt();
	}

	@Override
	public void toBytes(FriendlyByteBuf buf) {
		buf.writeVarInt(daveCoin);
		buf.writeVarInt(sunshine);
		buf.writeVarInt(plantFood);
	}

	@Override
	public void handler(Supplier<NetworkEvent.Context> supplier) {
		supplier.get().enqueueWork(() -> {
			NetworkUtils.syncSunshineData(sunshine);
			NetworkUtils.syncDaveCoinData(daveCoin);
			NetworkUtils.syncPlantFoodData(plantFood);
		});
		super.handler(supplier);
	}

	@Override
	public boolean canSend() {
		return sunshine >= 0 || daveCoin >= 0 || plantFood >= 0;
	}

	public static class NotificationServer extends PVZPacketBase implements CanSend {

		public NotificationServer() {
			super();
		}

		public NotificationServer(FriendlyByteBuf buf) {
			super(buf);
		}

		@Override
		public void toBytes(FriendlyByteBuf buf) {
		}

		@Override
		public void handler(Supplier<Context> supplier) {
			Context context = supplier.get();
			context.enqueueWork(() -> {
				ServerPlayer player = context.getSender();
				ManagerNetwork.sendToPlayer(new PlayerCapabilityPacket(player), player);
			});
			super.handler(supplier);
		}

		@Override
		public boolean canSend() {
			return true;
		}

	}

}
